<?php

namespace App\Store\Controllers\Goods\GoodsSend;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Common\Services\Store\Common as StoreCommon;


use App\Common\Services\CommonExcelExport;
use App\Store\Models\Account\SiteStore;
use App\Store\Models\Goods\GoodsSend\GoodsSendgoods;
use App\Store\Models\Goods\GoodsSend\GoodsSendgoodsAllot;
use App\Store\Models\Goods\GoodsSend\GoodsSendgoodsLog;
use App\Store\Models\Goods\GoodsSend\GoodsSendgoodsStock;
use Maatwebsite\Excel\Facades\Excel;
use App\Store\Services\Excel\DownloadTemp;

use App\Store\Validate\Goods\GoodsSend\GoodsSendgoods as ValidateGoodsGoodsSendGoodsSendgoods;
use Illuminate\Support\Facades\DB;

/**
 * 赠品调拨列表
 */
class GoodsSendgoodsAllotController extends Controller
{
    /**
     * 列表
     */
    public function getlist(Request $request)
    {
        $list = GoodsSendgoodsAllot::getList($request);
        return response()->json(['code' => '000', 'msg' => '获取成功', 'data' => $list]);
    }


    public function dodistributionmore(Request $request)
    {
        //审核后方可调拨
        $req_data = $request->only([
            'target_store_id', 'sendgoodslist', 'remark'
        ]);

        $cp_id = StoreCommon::getCurrentAccountCompanyId($request);
        $sendgoodslist=is_array($req_data['sendgoodslist'])?$req_data['sendgoodslist']:(is_array(json_decode($req_data['sendgoodslist'],true))?json_decode($req_data['sendgoodslist'],true):[]);
        if(count($sendgoodslist)<=0){
            return response()->json(['code' => '001', 'msg' => '调拨商品不能为空']);
        }
        $Validatesub = new ValidateGoodsGoodsSendGoodsSendgoods('dodistribution');
        foreach($sendgoodslist as &$val){
            $val['target_store_id']=$req_data['target_store_id'];
            if (!$Validatesub->check($val)) {
                return response()->json(['code' => '001', 'msg' => $Validatesub->getError()]);
            }

            $info = GoodsSendgoodsStock::where(['id' => $val['id'], 'cp_id' => $cp_id, 'is_del' => 1])->first();

            if (!$info) {
                return response()->json(['code' => '001', 'msg' => '参数错误']);
            }
            if($req_data['target_store_id']==$info->store_id){
                return response()->json(['code' => '001', 'msg' => '无效门店参数']);
            }

            $storeinfo = SiteStore::where(['id' => $req_data['target_store_id'], 'cp_id' => $cp_id])->first();
            if (!$storeinfo) {
                return response()->json(['code' => '001', 'msg' => '无效门店参数']);
            }
            if($val['count']>$info->count){
                return response()->json(['code' => '001', 'msg' => '调拨数量不能大于库存数量']);
            }

            $val['send_goods_info']=$info;

        }


        DB::beginTransaction();
        try {
            $sn_code=StoreCommon::createOrderSn();
            foreach($sendgoodslist as $vval){
                $info=$vval['send_goods_info'];
                GoodsSendgoodsAllot::create(
                    [
                    'cp_id' => $cp_id,
                    'store_id' => $info->store_id,
                    'target_store_id'=>$req_data['target_store_id'],
                    'sn_code'=>$sn_code,
                    'sendgoods_name'=>$info->sendgoods_name,
                    'goods_sn_code' => $info->goods_sn_code,
                    'count'=>$vval['count'],
                    'pieceprice'=>$info->pieceprice,
                    'create_at'=>time(),
                    'update_at'=>time(),
                    'remark'=>isset($vval['remark'])?$vval['remark']:'',
                    ]
                );
                GoodsSendgoodsStock::where(['id' => $vval['id'], 'cp_id' => $cp_id, 'is_del' => 1])
                    ->update(['count'=>DB::raw('count - ' . $vval['count'])]);   //减去库存

                    GoodsSendgoodsLog::create(
                        [
                        'cp_id' => $cp_id,
                        'store_id' =>  $info->store_id,
                        'target_store_id' =>$req_data['target_store_id'],
                        'type'=>4,
                        'sn_code'=>'',
                        'sendgoods_name'=>$info->sendgoods_name,
                        'goods_sn_code' => $info->goods_sn_code,
                        'count'=>$vval['count'],
                        'pieceprice'=>$info->pieceprice,
                        'create_at'=>time(),
                        'update_at'=>time(),
                        'remark'=>isset($vval['remark'])?$vval['remark']:'',
                        ]
                    );

            }

            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['code' => '001', 'msg' => '调拨失败' . $e->getMessage()]);
        }

        return response()->json(['code' => '000', 'msg' => '调拨操作成功']);


    }



    /**
     * 调拨审核
     */
    public function doauditsuccess(Request $request)
    {
        $id = $request->id ?? 0;
        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];
        if (!in_array($accountinfo['type'], [1, 2])) { //权限控制
            return response()->json(['code' => '001', 'msg' => '无权限，请使用门店端进行审核']);
        }
        $store_id = intval($accountinfo['store_ids']);
        // $store_id=9;
        $info = GoodsSendgoodsAllot::where(['id' => $id,'target_store_id'=>$store_id, 'cp_id' => $cp_id, 'is_del' => 1])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }
        if ($info->audit_status != 1) {
            return response()->json(['code' => '001', 'msg' => '该调拨单已审核']);
        }
        DB::beginTransaction();
        try {
            GoodsSendgoodsAllot::where(['id' => $id, 'cp_id' => $cp_id, 'is_del' => 1])->update(['audit_status'=>2,'audit_at'=>time()]);

            //审核后入库
            $stockinfo=GoodsSendgoodsStock::where(['cp_id' => $cp_id,'store_id' => $info->target_store_id,'goods_sn_code' => $info->goods_sn_code])->first();
            if($stockinfo){

                GoodsSendgoodsStock::where(['cp_id' => $cp_id,'store_id' => $info->target_store_id,'goods_sn_code' => $info->goods_sn_code])
                ->update(['count'=>DB::raw('count + ' . $info->count)]);

            }else{
                GoodsSendgoodsStock::create(
                    [
                    'cp_id' => $cp_id,
                    'store_id' => $info->target_store_id,
                    'sendgoods_name'=>$info->sendgoods_name,
                    'goods_sn_code' => $info->goods_sn_code,
                    'count'=>$info->count,
                    'pieceprice'=>$info->pieceprice,
                    'create_at'=>time(),
                    'update_at'=>time(),
                    'remark'=>$info->remark
                    ]
                );
            }
            //增加流水记录
            GoodsSendgoodsLog::create(
                [
                'cp_id' => $cp_id,
                'store_id' => $info->store_id,
                'target_store_id'=>$info->target_store_id,
                'type'=>3,
                'sn_code'=>'',
                'sendgoods_name'=>$info->sendgoods_name,
                'goods_sn_code' => $info->goods_sn_code,
                'count'=>$info->count,
                'pieceprice'=>$info->pieceprice,
                'create_at'=>time(),
                'update_at'=>time(),
                'remark'=>$info->remark
                ]
            );
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['code' => '001', 'msg' => '审核失败' . $e->getMessage()]);
        }

        return response()->json(['code' => '000', 'msg' => '调拨单审核成功']);
    }
    /**
     * 调拨审核取消
     */
    public function doauditcancel(Request $request)
    {
        $id = $request->id ?? 0;
        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];
        if (!in_array($accountinfo['type'], [1, 2])) { //权限控制
            return response()->json(['code' => '001', 'msg' => '无权限，请使用门店端进行审核']);
        }
        $store_id = intval($accountinfo['store_ids']);
        $info = GoodsSendgoodsAllot::where(['id' => $id,'target_store_id'=>$store_id, 'cp_id' => $cp_id, 'is_del' => 1])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }
        if ($info->audit_status != 1) {
            return response()->json(['code' => '001', 'msg' => '该调拨单已审核']);
        }
        GoodsSendgoodsAllot::where(['id' => $id, 'cp_id' => $cp_id, 'is_del' => 1])->update(['audit_status'=>3,'audit_at'=>time()]);

        GoodsSendgoodsStock::where(['cp_id' => $cp_id,'store_id' => $info->store_id,'goods_sn_code' => $info->goods_sn_code])
                ->update(['count'=>DB::raw('count + ' . $info->count)]);//恢复调拨库存
        GoodsSendgoodsLog::create(
            [
            'cp_id' => $cp_id,
            'store_id' =>  $info->target_store_id,
            'target_store_id' => $info->store_id,
            'type'=>6,
            'sn_code'=>'',
            'sendgoods_name'=>$info->sendgoods_name,
            'goods_sn_code' => $info->goods_sn_code,
            'count'=>$info->count,
            'pieceprice'=>$info->pieceprice,
            'create_at'=>time(),
            'update_at'=>time(),
            'remark'=>$info->remark
            ]
        );



        return response()->json(['code' => '000', 'msg' => '调拨审核取消成功']);
    }



    //批量审核

    public function doauditsuccessmore(Request $request)
    {

        $ids = $request->ids;
        $ids = is_array($ids) ? $ids : (is_array(json_decode($ids, true)) ? json_decode($ids, true) : []);

        if (count($ids) <= 0) {
            return response()->json(['code' => '001', 'msg' => '非目的门店的调拨单不能审核']);
        }
        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];

        if (!in_array($accountinfo['type'], [1, 2])) { //权限控制
            return response()->json(['code' => '001', 'msg' => '无权限，请使用门店端进行审核']);
        }
        $store_id = intval($accountinfo['store_ids']);

        $maininfocount = GoodsSendgoodsAllot::where(['cp_id' => $cp_id, 'target_store_id' => $store_id])->whereIn('id', $ids)->count();

        if ($maininfocount != count($ids)) {
            return response()->json(['code' => '001', 'msg' => '非目的门店的调拨单不能审核']);
        }
        $infolist = GoodsSendgoodsAllot::where(['cp_id' => $cp_id, 'target_store_id' => $store_id, 'audit_status' => 1])->whereIn('id', $ids)->get()->toArray();


        DB::beginTransaction();
        try {
            foreach ($infolist as $info) {
                $id = $info['id'];
                GoodsSendgoodsAllot::where(['id' => $id, 'cp_id' => $cp_id, 'is_del' => 1])->update(['audit_status'=>2,'audit_at'=>time()]);

                //审核后入库
                $stockinfo=GoodsSendgoodsStock::where(['cp_id' => $cp_id,'store_id' => $info['target_store_id'],'goods_sn_code' => $info['goods_sn_code']])->first();
                if($stockinfo){

                    GoodsSendgoodsStock::where(['cp_id' => $cp_id,'store_id' => $info['target_store_id'],'goods_sn_code' => $info['goods_sn_code']])
                    ->update(['count'=>DB::raw('count + ' . $info['count'])]);

                }else{
                    GoodsSendgoodsStock::create(
                        [
                        'cp_id' => $cp_id,
                        'store_id' => $info['target_store_id'],
                        'sendgoods_name'=>$info['sendgoods_name'],
                        'goods_sn_code' => $info['goods_sn_code'],
                        'count'=>$info['count'],
                        'pieceprice'=>$info['pieceprice'],
                        'create_at'=>time(),
                        'update_at'=>time(),
                        'remark'=>$info['remark']
                        ]
                    );
                }
                //增加流水记录
                GoodsSendgoodsLog::create(
                    [
                    'cp_id' => $cp_id,
                    'store_id' => $info['store_id'],
                    'target_store_id'=>$info['target_store_id'],
                    'type'=>3,
                    'sn_code'=>'',
                    'sendgoods_name'=>$info['sendgoods_name'],
                    'goods_sn_code' => $info['goods_sn_code'],
                    'count'=>$info['count'],
                    'pieceprice'=>$info['pieceprice'],
                    'create_at'=>time(),
                    'update_at'=>time(),
                    'remark'=>$info['remark']
                    ]
                );

            }

            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['code' => '001', 'msg' => '审核失败' . $e->getMessage()]);
        }

        return response()->json(['code' => '000', 'msg' => '调拨单审核成功']);



    }


    /**
     * 批量调拨审核取消
     */
    public function doauditcancelmore(Request $request)
    {
        $ids = $request->ids;
        $ids = is_array($ids) ? $ids : (is_array(json_decode($ids, true)) ? json_decode($ids, true) : []);

        if (count($ids) <= 0) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }
        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];

        if (!in_array($accountinfo['type'], [1, 2])) { //权限控制
            return response()->json(['code' => '001', 'msg' => '无权限，请使用门店端进行审核']);
        }
        $store_id = intval($accountinfo['store_ids']);

        $maininfocount = GoodsSendgoodsAllot::where(['cp_id' => $cp_id, 'target_store_id' => $store_id])->whereIn('id', $ids)->count();

        if ($maininfocount != count($ids)) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }
        $infolist = GoodsSendgoodsAllot::where(['cp_id' => $cp_id, 'target_store_id' => $store_id, 'audit_status' => 1])->whereIn('id', $ids)->get()->toArray();


        DB::beginTransaction();
        try {
            foreach ($infolist as $info) {
                $id = $info['id'];
                GoodsSendgoodsAllot::where(['id' => $id, 'cp_id' => $cp_id, 'is_del' => 1])->update(['audit_status'=>3,'audit_at'=>time()]);

                GoodsSendgoodsStock::where(['cp_id' => $cp_id,'store_id' => $info['store_id'],'goods_sn_code' => $info['goods_sn_code']])
                ->update(['count'=>DB::raw('count + ' . $info['count'])]);//恢复调拨库存

                GoodsSendgoodsLog::create(
                    [
                    'cp_id' => $cp_id,
                    'store_id' =>  $info['target_store_id'],
                    'target_store_id' => $info['store_id'],
                    'type'=>6,
                    'sn_code'=>'',
                    'sendgoods_name'=>$info['sendgoods_name'],
                    'goods_sn_code' => $info['goods_sn_code'],
                    'count'=>$info['count'],
                    'pieceprice'=>$info['pieceprice'],
                    'create_at'=>time(),
                    'update_at'=>time(),
                    'remark'=>$info['remark']
                    ]
                );


            }

            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['code' => '001', 'msg' => '审核失败' . $e->getMessage()]);
        }





        return response()->json(['code' => '000', 'msg' => '调拨审核取消成功']);
    }

    /**
     * 导出
     */
    public function doexport(Request $request)
    {
        $list = GoodsSendgoodsAllot::getList($request)['list'];
        $exceldata = [];
        $row = [
            ['start_store'=>'赠品调拨审核'],
            [
                'store_name' => '起始门店',
                'target_store_name' => '目的门店',
                'sn_code'=>"调拨编号",
                'goods_sn_code' => '货号',
                'sendgoods_name' => '赠品名称',
                'count' => '数量',
                'create_at' => '创建时间',
                'update_at' => '更新时间',
                'audit_status' => '状态',
                'remark' => '备注',
            ]
        ];
        foreach ($list as $val) {
            $exceldata[] = [
                'store_name' => $val['storeinfo']['store_name'],
                'target_store_name' => $val['targetstoreinfo']['store_name'],
                'sn_code'=>$val['sn_code'],
                'goods_sn_code' => $val['goods_sn_code'],
                'sendgoods_name' => $val['sendgoods_name'],
                'count' => $val['count'],
                'create_at' => date('Y-m-d H:i:s', $val['create_at']),
                'update_at' => date('Y-m-d H:i:s', $val['update_at']),
                'audit_status' => $val['audit_status'] == 1 ? '待审核' : ($val['audit_status'] == 2 ? '审核' : '取消'),
                'remark' => $val['remark'],
            ];
        }

        $filename = '赠品调拨信息导出_' . time() . '.xlsx';
        return Excel::download(new CommonExcelExport($row, $exceldata), $filename);
    }

}
